// pages/detail/detail.js
let WxParse = require('../../wxParse/wxParse.js');
let util=require("../../utils/util.js");
var baseImgUrl = util.baseImgUrl;
let app=getApp();
let openid;

var imageWidth ;//画布宽度
var imageHeight ;
var scaleRate;//缩放比
var imageTop;
let newslists;

let logoUrl = util.imgUrl + "kandianlogo.png";
let morenLogo = util.imgUrl + "logo.png";//用户头像，没有时用
var ewmPic =util.erweima;//二维码图片
var newsSrc = "";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    networkStatus: true,//网络状态 默认为true
    loadingStatus: false,//默认加载完成，true--正在加载中
    loadgif: util.imgUrl + "loading.gif",//加载gif图
    loading: util.imgUrl + "loading.png",
    none_network: util.imgUrl + "none_network.png",

    audio_bg: baseImgUrl + "audio_bg.png",//视频播放图片
    audio_s: baseImgUrl + "audio_s.png",
    wxPic: baseImgUrl + "wxPic.png",//发送给朋友
    friendsPic: baseImgUrl + "friendsPic.png",//生成海报
    scanPic: baseImgUrl + "scan.png",//图片浏览量
    shut2: baseImgUrl +"shut2.png",//关闭图片

    pageReady:true,
    pageReady2:true,
    baseImgUrl: baseImgUrl,
   
    greyshow:false,//是否显示分享的图片弹出框，默认为隐藏
    menushow: false,//是否显示分享选择框.默认为隐藏
   
    newstitle: "",
    avatar: "",
    authorName: "",
    au_openid:"",
    up_time: "",
    follow: 0,
    saveFlag: 0,
    contents:"",
    newslists: [],
    picurl: "",
    mineavatarUrl:"",

    visitedarr: [],//保存已读新闻的id
    
    hasdata:true,
    deleteBg: baseImgUrl +"deleteBg.png",

    isshare: 0,//是否是分享进入。默认0，不是
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("=====================detail onload");
   var that = this;
    //新闻的id
    var id;
    that.setData({
      loadingStatus: true
    })

    //可以在页面 onLoad 中去获取页面 url 中的参数( 下面 onShareAppMessage 函数中配置)
    if (options.isshare == 1) {
      console.log('是分享进入');
      this.setData({
        isshare: options.isshare
      })
    }

   
    wx.getNetworkType({
      success: function (res) {
        var networkType = res.networkType;
        if (networkType == "none" || networkType == "unknown") {
          that.setData({
            networkStatus: false
          })
        } else {
          that.setData({
            networkStatus: true,

          })
        }
      }, fail: function (err) {
        console.log("获取网络失败" + err);
        that.setData({
          networkStatus: false
        })
      }
    })

    if(options.newid){
       id = options.newid;
       that.setData({
         newid:options.newid
       })
     
    }else{
       id = 0;
    }
    //获取用户头像，存到缓存
    if(app.globalData.userInfo){
      var mineavatarUrl=app.globalData.userInfo.avatarUrl;
      wx.downloadFile({
        url: app.globalData.userInfo.avatarUrl,
      
        success: function (res) {
          console.log(res);
          that.setData({
            mineavatarUrl: res.tempFilePath,
          })
          that.data.mineavatarUrl = res.tempFilePath;
          console.log("我的头像图片");
          console.log(that.data.mineavatarUrl);
        }, fail: function (fres) {
          console.log("我的头像图片存缓存失败");
          that.setData({
            mineavatarUrl: morenLogo
          })
        }
      }) 
    }else{
      that.setData({
        mineavatarUrl:morenLogo
      })
    }
   
    
    //调用接口，获取新闻信息
    wx.request({
      url: util.zuopin_info,
      data: {
        id: options.newid,
        openid: app.globalData.openid
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success: function (data) {
         console.log(data);
        
        if (data.data.zuopin) {
         
          var res = data.data.zuopin;
          var title = res.title;
          var avatar = res.avatar;
          var up_time = res.up_time;
          var mcheng = res.user_nickname;
          var article = res.content;
          var follow = res.follow;
          var saveFlag = res.save;
          //获取分享图片的背景图
          var picurl;
          if (res.picurl) {
           picurl = res.picurl;

            wx.downloadFile({
              url: res.picurl,
              success: function (res) {
                
               
                picurl = res.tempFilePath;
                that.setData({
                  picurl: res.tempFilePath,
                })
                
              }, fail: function (fres) {
                  console.log("海报背景图存缓存失败");
                  that.setData({
                    picurl: util.imgUrl + "moren_bg.jpg",
                  })
              }
            })
          } else {
            console.log("返回接口picurl为空");
             picurl = util.imgUrl + "moren_bg.jpg";
            that.setData({
              picurl: util.imgUrl + "moren_bg.jpg",
            })
          }
          
          that.data.picurl = picurl;
          console.log("**************海报背景图 res.tempFilePath************");
          console.log(that.data.picurl);

          WxParse.wxParse('article', 'html', article, that, 0);
          that.setData({
            newstitle: title,
            avatar: avatar,
            authorName: mcheng,
            up_time: up_time,
            follow: follow,
            saveFlag: saveFlag,
            au_openid: res.uid,
           
            newslists: data.data.tuijian,
            loadingStatus: false,
          })

         
         
         
        } else {
          //接口没有返回值，页面读取默认值
          that.setData({
            loadingStatus: true
          })
        }

      },
      fail: function (err) {
        console.log("err" + err);
        that.setData({
          loadingStatus: true
        })
      }

    })

   
   },
  //点击进入发布人页面
  publisher:function(){
    wx.navigateTo({
      url: '/pages/publisher/publisher',
    })
  },

  //添加关注
  guanzhu:function(e){
    var that=this;
    
    var that=this;
    if (app.globalData.userInfo) {
      console.log("----------已授权----------------")
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      wx.request({
        url: util.guanzhu,
        data: {
          my_openid: app.globalData.openid,
          zuozheid: e.currentTarget.dataset.au_openid,
        },
        success: function (res) {
          // console.log(res);
          //修改关注值
          that.data.follow = 1;
          // var savef=e.currentTarget.dataset.savef;
          that.setData({
            follow: 1,//0--未关注，1--已关注

          })
        },
        fail: function (err) {
          console.log("err" + err)
        }
      })
    } else{
      console.log("未授权 ")
      wx.getUserInfo({
        success:function(res){
          console.log("请求授权并成功"+res);
          //请求关注接口
          wx.request({
            url: util.guanzhu,
            data: {
              my_openid: app.globalData.openid,
              au_openid: e.currentTarget.dataset.au_openid,

            },
            success: function (res) {
              console.log("关注成功" + res);
            },
            fail: function (err) {
              console.log("err" + err)
            }
          })
          //修改关注值
          that.data.follow = 1;
          // var savef=e.currentTarget.dataset.savef;
          that.setData({
            follow: 1,//0--未关注，1--已关注

          })
        },fail:function(err){
          console.log("请求授权失败")
        }
      })

    }
   
   
  },

  //取消关注
  quxiaoguanzhu:function(e){
    console.log(e);
    var that = this;
    console.log(app.globalData.openid);
    console.log(e.currentTarget.dataset.au_openid);
    //请求后台
    wx.request({
      url: util.quguan,
      data:{
        my_openid: app.globalData.openid,
        zuozheid: e.currentTarget.dataset.au_openid,
      },
      success:function(res){
        console.log("访问接口成功");
        console.log(res);
      },
      fail:function(err){
        console.log("err"+err)
      }
    })

    that.data.follow = 0;
    var savef = e.currentTarget.dataset.savef;
    that.setData({
     
        follow: 0,//0--未关注，1--已关注
       
    })
  },

  //收藏
  shoucang:function(e){
    var that = this;
    //请求后台，修改收藏值
    that.data.saveFlag = 1;
    var follow = e.currentTarget.dataset.follow;
    wx.request({
      url: util.shoucang,
      data:{
        my_openid: app.globalData.openid,
        newid:e.currentTarget.dataset.newid
      },
      success:function(res){
        console.log(res);
      },
      fail:function(err){
        console.log("err"+err);
      }
    })
    that.setData({
        follow: follow,//0--未关注，1--已关注
        saveFlag: 1,//0--未关注，1--已关注
        
    })
  },

  //取消收藏
  quxiaoshoucang:function(e){
    var that = this;
    //请求后台，修改收藏值
    that.data.saveFlag = 0;
    var follow = e.currentTarget.dataset.follow;
    wx.request({

      //新闻明细取消收藏
      url: util.qu_shoucang,
      data: {
        my_openid: app.globalData.openid,
        newid: e.currentTarget.dataset.newid
      },
      success: function (res) {
        console.log(res);
      },
      fail: function (err) {
        console.log("err" + err);
      }
    })
    that.setData({
     
        follow: follow,//0--未关注，1--已关注
        saveFlag: 0,//0--未关注，1--已关注
       
    })
  },

  
  //分享给朋友
  shareFriend:function(){
    wx.showShareMenu({
      withShareTicket: true
    })
    wx.updateShareMenu({
      withShareTicket: true,
      success:function(){ 
        console.log("success");
      },
      fail:function(){

      }
    })
  },

  //关闭分享图弹框
  shutgrey:function(){
    var that=this;
    that.setData({
      greyshow:false
    })
  },

  //显示分享选择菜单
  showchosemenu:function(){
    var that=this;
    that.setData({
      menushow:true
    })
  },
//隐藏分享选择菜单
  hidechosemunu:function(){
    var that = this;
    that.setData({
      menushow: false
    })
  },
  //生成海报提示
showLoading:function(){
  wx.showLoading({
    title: '正在生成海报',
  })
  setTimeout(function(){
    wx.hideLoading()
  },300)
},
  /********点击分享朋友圈 生成图片*************/
  formSubmit: function (e) {
    console.log(e);
    var that = this;

    this.setData({
      menushow: false,

    });
    wx.showToast({
      title: '正在生成海报...',
      icon: 'loading',
      duration: 1000
    });
    setTimeout(function () {
      wx.hideToast()
      that.createNewImg();
      that.setData({
        greyshow: true
      });
    }, 2000)
  },

  //将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
  createNewImg: function () {
    var that = this;
    var context = wx.createCanvasContext('mycanvas');
    context.setFillStyle("#fff")
    context.fillRect(0, 0, 690, 750);
    // context.fillRect(10, imageTop, imageWidth, imageHeight)

    /***********图片路径********************/
     var pathurl = that.data.picurl;//分享图背景图
    console.log(pathurl);
   //绘制上部图片
    context.drawImage(pathurl,0, 0, 375, 420);
    
    var path2=that.data.mineavatarUrl ;//用户的头像图
   console.log("-------------------canvas-------------");
   console.log(path2);
    var path3 = util.imgUrl+"kandianlogo.png";//同城看点logo图
    var path4 = util.erweima;//二维码图片
    var path5 = util.imgUrl+"friendsPic.png";//分享朋友圈图片
    var pathline = util.imgUrl+"shortline.png";//直线
    var nickname = "nickName";//作者名
    if (app.globalData.userInfo.nickName){
      nickname = app.globalData.userInfo.nickName;//作者名
    }
    
    
     //绘制logo
    context.drawImage(path3, 210, 150, 150, 40);

    //不知道是什么原因，手机环境能正常显示
    // context.save(); // 保存当前context的状态

   
    //绘制名字
    context.setFontSize(26);
    context.setFillStyle('#333333');
    context.setTextAlign('left');
    context.font = "weight";
    /**********文章标题********/
    var newstitle = that.data.newstitle;//后台传的标题内同
  
    /**********换行**开始*******/
    var chr = newstitle.split("");//这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < 345) {
        temp += chr[a];
      }
      else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);

    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < 330) {
          test += rowPart[a];
        }
        else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..."//这里只显示两行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      console.log("----------------enter-----------")
      context.fillText(row[b], 15, 460 + b * 40, 345);
      
    }
    context.stroke();
    
    //绘制直线
    context.drawImage(pathline, 15, 520, 345, 1, 82);
    context.setFillStyle('#efefef');
    context.stroke();

    //绘制左下角二维码
    context.drawImage(path4, 15, 530, 100, 120);
    context.setFillStyle('#efefef');
    context.stroke();



    

    //绘制右下角上侧文字
    context.setFontSize(14);
    context.setFillStyle('#333');
    context.setTextAlign('left');
   

    /**********用户名**开始*******/
    
     nickname = nickname.split("");//这个方法是将一个字符串分割成字符串数组
    var temp2 = "";
    var row2 = [];
   
      for (var a = 0; a < nickname.length; a++) {
        if (context.measureText(temp2).width < 70) {
          temp2 += nickname[a];
        }
        else {
          a--; //这里添加了a-- 是为了防止字符丢失
          row2.push(temp2);
          temp2 = "";
        }
      }
      row2.push(temp2);
      console.log("row2" + row2);

      //如果数组长度大于1 则截取第1个
      if (row2.length > 1) {
        var rowCut2 = row2.slice(0, 1);//第一条需要截取的字符
        console.log(rowCut2);
        var rowPart2 = rowCut2[0];
        console.log("rowPart2" + rowPart2)
        var test2 = "";
        var empty2 = [];
        for (var a = 0; a < rowPart2.length; a++) {
          if (context.measureText(test2).width < 60) {
            test2 += rowPart2[a];
          }
          else {
            break;
          }
        }
        empty2.push(test2);
        console.log(empty2);
        var group2 = empty2[0] + "..."//

         rowCut2.splice(0, 1, group2);


      
        context.fillText(rowCut2[0], 190, 570, 70);
    }else{
        context.fillText(row2, 190, 570, 70);
    }

    
    context.stroke();


    /*****************************************/
    context.setFontSize(14);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText("正在浏览文章", 270, 570, 164);
    context.stroke();

    //绘制右下角下侧文字
    context.setFontSize(14);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText("识别小程序，进入", 130, 630);
    context.stroke();

    context.setFontSize(14);
    context.setFillStyle('#ff1313');
    context.setTextAlign('left');
    context.fillText("同城看点", 241, 630);
    context.stroke();

    context.setFontSize(14);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText("浏览文章", 300, 630);
    context.stroke();
  
    //绘制右下角上侧logo图
    context.arc(155, 565, 25, 0, 2 * Math.PI) //画出圆
    context.strokeStyle = "#efefef";
    context.clip(); //裁剪上面的圆形

    context.drawImage(path2, 130, 540, 50, 50, 50, 50);
    context.setFillStyle('#efefef');
    context.stroke();
    context.stroke();

    context.draw();


    //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
    setTimeout(function () {
      wx.canvasToTempFilePath({
        x:0,
        y:133,
        width:690,
        height:750,
        destHeight:750,
        destWidth:690,
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath,
            canvasHidden: true
          });
          that.baocun();
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 200);
  },

  //点击保存到相册
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        console.log("图片保存成功")
        // wx.showModal({
        //   content: '图片已保存到相册，赶紧晒一下吧~',
        //   showCancel: false,
        //   confirmText: '好的',
        //   confirmColor: '#333',
        //   success: function (res) {
        //     if (res.confirm) {
        //       console.log('用户点击确定');
        //       /* 该隐藏的隐藏 */
        //       that.setData({
        //         maskHidden: false
        //       })
        //     }
        //   }, fail: function (res) {
        //     console.log(11111)
        //   }
        // })
      }
    })
  },

  /********点击推荐 跳转页面****** */
  gotodetail:function(e){
    var that=this;
    var thisid=e.currentTarget.dataset.id;
    that.data.visitedarr.push(thisid);
    wx.navigateTo({
      url: '/pages/detail/detail?newid=' + thisid,
    })

  },

  /*********跳转到视频详情************* */
  audiodetail:function(e){
    var that = this;
    var thisid = e.currentTarget.dataset.id;
    that.data.visitedarr.push(thisid);
    wx.navigateTo({
      url: '/pages/audio/audio?newid=' + e.currentTarget.dataset.id,
    })
  },
  
    // wx.getImageInfo({
    //   src: 'http://ones.cakeyouxuan.com/public/white_bg.png',//服务器返回的带参数的小程序码地址
    //   success: function (res) {
    //     //res.path是网络图片的本地地址
    //     qrCodePath = res.path;
    //   },
    //   fail: function (res) {
    //     //失败回调
    //   }
    // });
 

  onReady:function(){
    var that=this;
    
    setTimeout(function(){
      that.setData({
        pageReady: true
      })
    },200)
    setTimeout(function(){
      wx.hideLoading();
      that.setData({
        pageReady2: true
      })

    },400)
   
  },

  onShow:function(){
    var that = this;
    var newsLen = that.data.newslists.length;
    var visitLen = that.data.visitedarr.length;
    console.log("----------detail onshow--------------");
    console.log(that.data.visitedarr);

    for (var i = 0; i < newsLen; i++) {
      for (var j = 0; j < visitLen; j++) {
        if (that.data.newslists[i].id == that.data.visitedarr[j]) {
          that.data.newslists[i].visited = true;

          that.setData({
            newslists: that.data.newslists
          })
        }
      };
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that=this;
    return {
      title: that.data.newstitle,
      path: '/pages/detail/detail?isshare=1&&newid='+that.data.newid,
      success: function (res) {
        // 转发成功
        console.log("================success");
        console.log(that.data.isshare);
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  /**
   * 回到首页(分享的时候)
   */
  backHome: function () {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  }

})
